package monitorprocess

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

var pwd string

func GetPWD() string {
	return pwd
}

func init() {

	ex, _ := os.Executable()
	pwd = filepath.Dir(ex)
	fmt.Println("------------", pwd)

	//f, err := os.Create(pwd + "/service.log")

	//log.SetOutput(f)
}
func findWrong(pnames []string) []string {
	result := make([]string, 0, len(pnames))
	for _, name := range pnames {
		pids, err := findPID(name)
		if err != nil {
			return pnames
		}
		if len(pids) != 1 {
			result = append(result, name)
		}
	}
	return result
}
func killByName(name string) {
	killstr := name + ".exe"
	cmd := exec.Command("taskkill", "/f", "/im", killstr)
	log.Println("taskkill --------", killstr)
	out, err := cmd.CombinedOutput()
	log.Println("kill --------", killstr, string(out), err)

}

func startByName(name string) {
	start := pwd + "/" + name + ".exe"
	cmd := exec.Command(start)
	err := cmd.Start()
	log.Println("start --------", start, err)
}

func Restart(pnames []string) {
	for _, name := range pnames {
		killByName(name)
		startByName(name)
	}
}

func findPID(pname string) ([]string, error) {
	findstr := "imagename eq " + pname + ".exe"
	cmd := exec.Command("tasklist", "/fi", findstr)
	out, err := cmd.CombinedOutput()
	if err != nil {
		log.Panicln(err)
	}
	lines := strings.Split(string(out), "\r\n")
	//fmt.Println("!!!!!!!!!!!!!", len(lines), lines[0], string(out))
	lineCount := len(lines)
	if lineCount >= 2 {
		linePos := 0
		pidPos := 0
		for i, line := range lines {
			if len(line) > 0 {
				if pidPos == 0 {
					titles := strings.Fields(line)
					for j, v := range titles {
						if v == "PID" {
							pidPos = j
							break
						}
						fmt.Println("-------", v)
					}
					if pidPos == 0 {
						return nil, errors.New("没有找到进程")
					}

				} else if strings.HasPrefix(line, "==") {
					linePos = i + 1
					break
				}
			}
		}
		if linePos != 0 && pidPos != 0 {
			result := make([]string, 0, lineCount-linePos)
			for i := linePos; i < lineCount; i++ {
				values := strings.Fields(lines[i])
				if len(values) > pidPos {
					result = append(result, values[pidPos])
				}
			}
			return result, nil

		}
		return nil, errors.New("没有找到进程")
	}
	return nil, errors.New("命令格式错误 line1")

}

func Run() {
	if stopAll {
		return
	}
	str := ""
	f, err := ioutil.ReadFile(pwd + "/pnames")
	fmt.Println("*******", pwd)
	if err != nil {
		fmt.Println("read fail", err)
		str = "tm,dm,box"
		fp, errf := os.Create(pwd + "/pnames")
		if fp != nil && errf == nil {
			io.WriteString(fp, str)
		}

	} else {
		str = string(f)
	}
	pnames := strings.Split(str, ",")
	wrongs := findWrong(pnames)
	if wrongs != nil {
		log.Println("---------restart pnames---------", wrongs)
		Restart(wrongs)
	}
	if stopAll {
		KillAll(true)
	}
}

var stopAll bool

func KillAll(isStop bool) {
	str := ""
	stopAll = isStop
	f, err := ioutil.ReadFile(pwd + "/pnames")
	if err != nil {
		fmt.Println("read fail", err)
		str = "tm,dm,box"
		fp, errf := os.Create(pwd + "/pnames")
		if fp != nil && errf == nil {
			io.WriteString(fp, str)
		}

	} else {
		str = string(f)
	}
	pnames := strings.Split(str, ",")
	for _, name := range pnames {
		killByName(name)
	}
	log.Println("kill all------", pnames)

}
